#include <QFile>
#include <QFileInfo>
#include <QTextStream>
#include "database-manager.h"
#include "file-error.h"
#include "fcntl.h"
#include <stdlib.h>

using namespace Core;

DatabaseManager::DatabaseManager(const QString& storageName) : QObject()
{
    level = 0;
    storageDir.mkpath(databaseRootPath());
    storageDir.setPath(databaseRootPath());
    storageDir.mkdir(storageName);
    storageDir.cd(storageName);

    listDir.setPath(storageDir.path());
    listDir.mkdir("lists");
    listDir.cd("lists");
}

void DatabaseManager::startSubStorage(const QString &subStorageName)
{
    level++;
    storageDir.mkdir(subStorageName);
    storageDir.cd(subStorageName);
}

void DatabaseManager::finishSubStorage()
{
    if (level == 0)
        return;

    level--;
    storageDir.cdUp();
}

QString DatabaseManager::databaseRootPath()
{
    return "Database";
}

void DatabaseManager::store(const QString &fileName, const QString &data)
{
    QFile file(QFileInfo(storageDir.path(), fileName).filePath());
    if (!file.open(QIODevice::WriteOnly))
        throw new EFileError(QString("Cannot store Oxford word '%1': %2").arg(fileName).arg(file.errorString()));

    QTextStream writer(&file);
    writer << data.toUtf8();

    file.close();
}

QString DatabaseManager::read(const QString &fileName)
{
    QFile file(QFileInfo(storageDir.path(), fileName).filePath());
    if (!file.open(QIODevice::ReadOnly))
        throw new EFileError(QString("Cannot read file '%1': %2").arg(fileName).arg(file.errorString()));

    QTextStream reader(&file);
    return reader.readAll();
}

bool DatabaseManager::exists(const QString &fileName)
{
    return QFile::exists(QFileInfo(storageDir.path(), fileName).filePath());
}

void DatabaseManager::storeList(const QString &name, const QStringList &items)
{
    QFile file(QFileInfo(listDir.path(), name + ".lst").filePath());
    if (!file.open(QIODevice::WriteOnly))
        throw new EFileError(QString("Cannot store list '%1': %2").arg(name).arg(file.errorString()));

    QTextStream writer(&file);
    writer << items.join("\n").toUtf8();

    file.close();
}

QString DatabaseManager::getRandomListItem(const QString &listName)
{
    QFile file(QFileInfo(listDir.path(), listName + ".lst").filePath());
    if (!file.open(QIODevice::ReadOnly))
        throw new EFileError(QString("Cannot read list '%1': %2").arg(listName).arg(file.errorString()));

    QTextStream reader(&file);
    QStringList data = reader.readAll().split("\n");
    return data[qrand() * data.size() / RAND_MAX];
}

QStringList DatabaseManager::getList(const QString &name)
{
    QFile file(QFileInfo(listDir.path(), name + ".lst").filePath());
    if (!file.open(QIODevice::ReadOnly))
        throw new EFileError(QString("Cannot read list '%1': %2").arg(name).arg(file.errorString()));

    QTextStream reader(&file);
    return reader.readAll().split("\n");
}
